<template>
  <div class="supervise-mine-flow-bug"
       :class="{
      'print-supervise': !showPagination
    }">
    <div class="main-tab"
         v-if="isAdmin">
      <a-menu v-model="activeTabKeyList"
              mode="horizontal"
              @select="onSelectTab">
        <a-menu-item v-for="item in tabList"
                     :key="item.key"
                     :title="item.label">{{ item.label }}
        </a-menu-item>
      </a-menu>
    </div>
    <div class="condition-content"
         :id="searchConditionContainerId"></div>
    <div class="main-header">
      <div class="toolbar">
        <CommonToolbar :allToolBtns="allToolBtns"
                       @buttonClick="buttonClick"> </CommonToolbar>
      </div>
      <div class="search-part">
        <a-input-search class="search-input"
                        :placeholder="$i18n('collaboration.new.template.search.keyWords')"
                        :allowClear="true"
                        @search="onSearch" />
        <div class="search-button">
          <SearchCondition class="search-condition"
                           :containerParentId="searchConditionContainerId"
                           :conditions="searchConditions"
                           @valueChange="conditionValueChange"></SearchCondition>
        </div>
      </div>
    </div>
    <div class="main-content"
         ref="tableContent">
      <AVirtuallyTable ref="table"
                       :row-selection="{
          columnWidth: 60,
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          onSelect: onSelectRecord,
          type: 'radio'
        }"
                       rowKey="id"
                       size="small"
                       :pagination="showPagination"
                       :paginationOption="pagination"
                       :columns="columns"
                       :loading="tableLoading"
                       :openVirtuallyModel="true"
                       :dataSource="dataSource"
                       :titleRightMenus="titleRightMenus"
                       :localstorageKey="getLocalStorageKey"
                       @paginationChange="handleTableChange"
                       @paginationShowSizeChange="paginationShowSizeChange">
        <span @click="
            titleClick(record, {
              managerType: urlParamObj.managerType,
              dataType: dataType
            })
          "
              slot="subject"
              :title="text"
              class="pointer"
              slot-scope="{ text, record }">
          <i class="danger-color"
             :class="'xicon-important' + (record.importantLevel - 1)"
             v-if="
              record.importantLevel != '' &&
              record.importantLevel != -1 &&
              record.importantLevel != 1
            "></i>
          {{ text }}
        </span>

        <span class="pointer link-color"
              slot="startMemberName"
              :title="text"
              @click="startMemberNameClick(record.startMemberId)"
              slot-scope="{ text, record }">
          {{ text }}
        </span>
        <span class="pointer link-color"
              slot="processLog"
              slot-scope="{ record }"
              @click="showDetailLogDialog(record.summaryId, record.processId, 2, record.affairId)">
          <i class="xicon-form-text"></i>
        </span>
        <span class="pointer link-color"
              slot="bugMemberName"
              :title="text"
              @click="startMemberNameClick(record.bugMemberId)"
              slot-scope="{ text, record }">
          {{ text }}
        </span>
        <span slot="attName"
              slot-scope="{ text, record }">
          <span :title="text"
                class="pointer link-color"
                @click="showAtt(record.id)"
                v-if="text">
            {{ text }}
          </span>
          <span v-else>
            {{ i18n('common.default') }}
          </span>
        </span>
      </AVirtuallyTable>
    </div>
  </div>
</template>

<script>
  import CommonToolbar from '@/components/common-toolbar/index';
  import SearchCondition from '@/components/search-condition/index.vue';

  import AVirtuallyTable from '@/ant-virtually-table/table.vue';
  import { getParams } from '@/utils';
  import { formatRequestDataToJSON, loadExtendResource } from '@/utils/api';

  import superviseMixin from '@/mixins/supervise/supervise-mixin.js';
  import * as Fiber from 'fiber';
  const urlParamObj = getParams(window.location.search);
  export default {
    name: 'SuperviseMineFlowBug',
    components: {
      CommonToolbar,
      SearchCondition,
      AVirtuallyTable
    },
    props: ['dataType', 'state', 'needStatisticsVal', 'statisRecieveData'],
    mixins: [superviseMixin],
    data() {
      return {
        searchConditionContainerId: 'search-condition-container-parent',
        dataSource: [],
        columns: [],
        selectedRowKeys: [],
        urlParamObj: {},
        titleRightMenus: {
          asc: true,
          desc: true,
          freeze: true,
          fieldset: true
        },
        pagination: {
          page: 1,
          total: 0
        },
        searchValue: '',
        selectedRows: [],
        searchConditions: [],
        isAdmin: false,

        activeTabKeyList: ['0'],
        tabList: [
          {
            key: '0',
            label: $.i18n('workflow.bug.not.deal')
          },
          {
            key: '1',
            label: $.i18n('common.detail.label.done')
          }
        ],
        advancedParams: null,
        showPagination: true,
        tableLoading: false
      };
    },
    computed: {
      getLocalStorageKey() {
        return window._currentUser.id + 'SUPERVISE_STATISTIC';
      },
      activeTabKey() {
        return this.activeTabKeyList && this.activeTabKeyList[0];
      },
      allToolBtns() {
        const allMenuList = [
          {
            //编辑流程
            id: 'editWorkFlow',
            name: $.i18n('common.design.workflow.label')
          },
          {
            //流程终止
            id: 'processEnd',
            name: $.i18n('supervise.process.End')
          },
          {
            //流程撤销
            id: 'processRevoke',
            name: $.i18n('common.toolbar.repeal.label')
          },
          {
            //标为已处理
            id: 'dealProblem',
            name: $.i18n('workflow.bug.set.already.deal.js')
          },
          {
            //导出
            id: 'exportExcel',
            name: $.i18n('common.export.label')
          },
          {
            // 打印
            id: 'print',
            name: $.i18n('common.toolbar.print.label')
          }
        ];
        const showMenuMap = {
          editWorkFlow: {
            show: this.activeTabKey === '0'
          },
          processEnd: {
            show: this.activeTabKey === '0'
          },
          processRevoke: {
            show: this.activeTabKey === '0'
          },
          dealProblem: {
            show: this.activeTabKey === '0'
          },
          exportExcel: {
            show: this.activeTabKey === '0'
          },
          print: {
            show: true
          }
        };
        const showMenuList = allMenuList.filter((menu) => {
          return showMenuMap[menu.id]?.show;
        });
        return showMenuList;
      }
    },
    watch: {
      dataType() {
        this.initPageMetaData({
          superviseBoxType: this.dataType
        });
      }
    },
    created() {
      this.activeTabKeyList = [this.state ?? '0'];
      this.columnMap = {
        subject: {
          // 标题
          dropdownMenus: {
            asc: false,
            desc: false,
            freeze: true,
            fieldset: true
          },
          scopedSlots: { customRender: 'subject' },
          customCell: () => {
            return {
              style: {
                cursor: 'pointer'
              }
            };
          }
        },
        startMemberName: {
          // 发起人
          dropdownMenus: {
            asc: false,
            desc: false,
            freeze: true,
            fieldset: true
          },
          scopedSlots: { customRender: 'startMemberName' }
        },
        startDate: {
          // 发起时间
          dropdownMenus: {
            asc: false,
            desc: false,
            freeze: true,
            fieldset: true
          }
        },
        processLog: {
          // 流程日志
          dropdownMenus: {
            freeze: true,
            fieldset: true
          },
          scopedSlots: { customRender: 'processLog' }
        },
        bugTypeName: {
          // 问题分类
          dropdownMenus: {
            asc: false,
            desc: false,
            freeze: true,
            fieldset: true
          }
        },
        bugMemberName: {
          // 问题上报人
          dropdownMenus: {
            asc: false,
            desc: false,
            freeze: true,
            fieldset: true
          },
          scopedSlots: { customRender: 'bugMemberName' }
        },
        bugDescription: {
          // 上报附言
          dropdownMenus: {
            asc: false,
            desc: false,
            freeze: true,
            fieldset: true
          }
        },
        attName: {
          // 流程异常附件
          dropdownMenus: {
            asc: false,
            desc: false,
            freeze: true,
            fieldset: true
          },
          scopedSlots: { customRender: 'attName' }
        }
      };

      this.initPageMetaData({
        superviseBoxType: this.dataType
      });
    },
    methods: {
      i18n(val) {
        return $.i18n(val);
      },
      initTableData(params) {
        this.$refs.table.cleanSelection();
        this.tableLoading = true;
        let url = `${window._ctxPath}/ajax.do`;
        let urlParms = {
          method: 'ajaxAction'
        };
        let cachParams = {
          state: this.activeTabKey,
          subject: this.searchValue || '',
          ...(urlParamObj.templeteIds && { operationTypeIds: urlParamObj.templeteIds }),
          ...(this.globalParam.templateIds &&
            !urlParamObj.templeteIds && { operationTypeIds: this.globalParam.templateIds }),
          ...this.advancedParams,
          ...params
        };

        this.cachParams = cachParams;

        const sendParams = [
          { page: this.pagination.page, size: this.pagination.pageSize },
          cachParams
        ];
        urlParms.managerName = 'workflowBugReportManager';
        urlParms.managerMethod = 'workflowBugList';

        url = this.mergeUrlParams(url, urlParms);

        const args = `&arguments=${formatRequestDataToJSON(sendParams)}`;

        if (this.cancelToken && this.cancelToken.cancel) {
          this.cancelToken.cancel();
          this.cancelToken = null;
        }
        this.cancelToken = axios.CancelToken.source();

        window.axios
          .post(url, args, {
            cancelToken: this.cancelToken.token,
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
            }
          })
          .then((data) => {
            const result = data.data;
            if (result) {
              this.pagination.total = result.total;
              this.dataSource = result.data;
              if (this.statisRecieveData?.pageHead) {
                let curItem = this.statisRecieveData.pageHead.items.find((item) => {
                  return item.key === this.dataType;
                });

                // curItem && (curItem.value = result.total);
                this.$emit('updadeStatisticsBar', this.statisRecieveData);
              }
            }
            this.tableLoading = false;
          });
      },
      onSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys;
      },
      onSelectRecord(record, selected, selectedRows) {
        this.selectedRows = selectedRows;
      },
      onSearch(e) {
        this.searchValue = e;
        this.pagination.page = 1;
        this.initTableData();
      },
      //按钮点击事件
      buttonClick(buttonKey) {
        switch (buttonKey) {
          case 'print':
            this.showPagination = false;
            this.$nextTick(() => {
              this.popprint(this.$el.outerHTML);
              this.showPagination = true;
            });
            return;
          case 'exportExcel':
            this.exportExcel(this.cachParams, this.pagination.total, {
              managerType: urlParamObj.managerType,
              dataType: this.dataType
            });
            return;
          default:
            break;
        }
        if (this.selectedRowKeys.length < 1) {
          Fiber.message.warning($.i18n('supervise.please.select.operation.data'));
          return;
        }

        switch (buttonKey) {
          case 'editWorkFlow':
            var row = this.selectedRows[0];
            this.editFlowChart(
              row,
              {
                saveDBOK: {
                  show: true,
                  callback: () => {
                    this.initTableData();
                  }
                },
                repeal: {
                  show: true,
                  callback: () => {
                    this.initTableData();
                  }
                },
                stop: {
                  show: true,
                  callback: () => {
                    this.initTableData();
                  }
                },
                close: {
                  show: true,
                  callback: () => {}
                }
              },
              {
                managerType: urlParamObj.managerType,
                dataType: this.dataType
              }
            );
            break;
          case 'processEnd':
            var row = this.selectedRows[0];
            this.stopFlowChart(
              row,
              () => {
                this.initTableData();
              },
              { dataType: this.dataType }
            );
            break;
          case 'processRevoke':
            var row = this.selectedRows[0];
            this.repealflowChart(
              row,
              () => {
                this.initTableData();
              },
              { dataType: this.dataType }
            );
            break;
          case 'dealProblem':
            var row = this.selectedRows[0];
            this.dealflowChart(row, () => {
              this.initTableData();
            });
            break;
          default:
            break;
        }
      },
      handleTableChange(page, pageSize) {
        this.pagination.page = page;
        this.pagination.pageSize = pageSize;
        this.initTableData();
      },
      initPageMetaData({ superviseBoxType, callback } = {}) {
        if (!superviseBoxType) {
          return;
        }
        let memberIdStr = urlParamObj.memberId ? decodeURIComponent(urlParamObj.memberId) : '';
        const headerParams = {
          // 页面唯一标识（取值参照PageKey）
          key: 'SUPERVISE_WORKFLOW_PROBLEM',
          // 终端 0 pc 1 mobile （取值参照PlatformType）
          platform: 0,
          // 业务传参，由业务决定（后续可在元数据拦截器中获取到）
          arguments: {
            managerType: urlParamObj.managerType,
            superviseBoxType: superviseBoxType,
            boardId: urlParamObj?.boardId || '',
            memberId: memberIdStr || '',
            needStatisticsVal: false
          }
        };
        const url = `${window._ctxPath}/rest/global/metadata/list`;

        window.axios.post(url, headerParams).then((data) => {
          if (data.data.code === 0) {
            const recieveData = data.data.data;
            loadExtendResource(recieveData.extra?.extendResources);
            this.globalParam = recieveData.globalParam || {};
            this.isAdmin = this.globalParam?.groupAdmin || this.globalParam?.administrator;
            if (superviseBoxType) {
              recieveData.tableColumns.forEach((col) => {
                col.dataIndex = col.key;
                col.ellipsis = true;
                Object.assign(col, this.columnMap[col.key]);
              });
              this.columns = recieveData.tableColumns.filter((item) => item.key !== 'id');
              this.searchConditions = recieveData.searchConditions.filter((item) => {
                item.isAdministrator = this.globalParam?.administrator;
                item.managerType = urlParamObj?.managerType;
                return item.key !== 'subject';
              });
              this.initTableData();
            }

            callback && callback();
          }
        });
      },
      mergeUrlParams(url, params) {
        const paramsKeys = Object.keys(params);
        paramsKeys.forEach((key, index) => {
          if (params[key] !== undefined) {
            if (index === 0) {
              url += '?';
              url += `${key}=${params[key]}`;
            } else {
              url += `&${key}=${params[key]}`;
            }
          }
        });
        return url;
      },
      startMemberNameClick(startMemberId) {
        window.showV3XMemberCard(startMemberId, window);
      },
      showAtt(workflowBugId) {
        var dialog = $.dialog({
          url:
            _ctxPath +
            '/workflow/designer.do?method=workflowProblemAtts&workflowBugId=' +
            workflowBugId +
            CsrfGuard.getUrlSurffix(),
          width: 500,
          height: 250,
          title: $.i18n('workflow.bug.att.js'), //流程异常附件
          targetWindow: window.getCtpTop()
        });
      },
      onSelectTab() {
        this.selectedRowKeys = [];
        this.$nextTick(() => {
          this.initTableData();
        });
      },
      conditionValueChange(data) {
        this.pagination.page = 1;
        if (data && Object.keys(data).length) {
          let params = {};
          for (let key in data) {
            switch (key) {
              case 'createDate':
                for (let k in data[key]) {
                  const keyMap = {
                    startDate: 'beginDate',
                    endDate: 'endDate'
                  };
                  params[keyMap[k]] = data[key][k];
                }
                break;
              case 'problemState':
                params.state = data[key];
                break;
              case 'bugMemberStr':
                params.bugMemberId = data[key].value;
                break;
              case 'startMemberName':
                params.senders = data[key].value;
                break;
              default:
                break;
            }
          }
          this.advancedParams = params;
        } else {
          this.advancedParams = null;
        }
        this.initTableData();
      },
      paginationShowSizeChange(current, size) {
        this.pagination.pageSize = size;
        this.initTableData();
      }
    },
    mounted() {}
  };
</script>

<style lang="scss">
  .supervise-mine-flow-bug {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;

    * {
      box-sizing: border-box;
    }

    .main-header {
      padding: 12px 16px 12px 16px;
      height: 54px;
      display: flex;

      .toolbar {
        flex: 1;
        overflow: hidden;
      }

      .search-part {
        display: flex;
        justify-content: flex-end;
        overflow: hidden;
        margin-left: 100px;

        .search-input {
          width: 272px;
        }

        .search-button {
          margin-left: 12px;
        }
      }
    }

    .main-content {
      padding: 0 20px;
      flex: 1;
      overflow: hidden;
    }

    .pointer {
      cursor: pointer;
    }
    .link-color {
      // color: var(--theme-brand6, #1f85ec);
      color: #2490f8;
      color: var(--theme-brand5, #2490f8);
    }
    .xicon-form-text {
      color: #1f85ec;
    }
    .danger-color {
      color: #fb3a36;
    }
  }

  .print-supervise {
    .condition-content {
      display: none;
    }
    .main-header {
      display: none;
    }
    .search-part {
      display: none;
    }
    .search-input {
      display: none;
    }
    .search-condition {
      display: none;
    }
    .search-condition-container {
      display: none;
    }
    .ant-table-body {
      height: auto !important;
      max-height: none !important;
    }
    .scrollbar {
      display: none;
    }
  }
</style>
